package org.amphiprion.diceroller.dao.db;

import java.util.ArrayList;
import java.util.List;

import org.amphiprion.diceroller.entity.GamePreset;

import android.content.Context;
import android.database.Cursor;

public class GamePresetDao extends AbstractDbDao {
	private static GamePresetDao instance;

	/**
	 * Hidden constructor.
	 * 
	 * @param context
	 *            the application context
	 */
	private GamePresetDao(Context context) {
		super(context);
	}

	/**
	 * Return the singleton.
	 * 
	 * @param context
	 *            the application context
	 * @return the singleton
	 */
	public static GamePresetDao getInstance(Context context) {
		if (instance == null) {
			instance = new GamePresetDao(context);
		}
		return instance;
	}

	public void persist(GamePreset entity) {
		if (isInDb(entity.getId())) {
			update(entity);
		} else {
			create(entity);
		}
	}

	public void delete(GamePreset entity) {
		String sql = "delete from game_preset where id=?";

		Object[] params = new Object[1];
		params[0] = entity.getId();
		execSQL(sql, params);
	}

	private void create(GamePreset entity) {
		String sql = "insert into game_preset (" + "id, game_path, name, dices" + ") values (?,?,?,?)";

		Object[] params = new Object[4];
		params[0] = entity.getId();
		params[1] = entity.getGamePath();
		params[2] = entity.getName();
		params[3] = entity.getDices();
		execSQL(sql, params);

	}

	private void update(GamePreset entity) {
		String sql = "update game_preset set game_path=?, name=?, dices=? where id=?";

		Object[] params = new Object[4];
		params[0] = entity.getGamePath();
		params[1] = entity.getName();
		params[2] = entity.getDices();
		params[3] = entity.getId();

		execSQL(sql, params);

	}

	public List<GamePreset> getPresets(String gameDir) {
		String sql = "select " + "id, game_path, name, dices from game_preset where game_path=? order by name";

		String[] params = new String[1];
		params[0] = gameDir;

		Cursor cursor = getDatabase().rawQuery(sql, params);
		ArrayList<GamePreset> result = new ArrayList<GamePreset>();

		if (cursor.moveToFirst()) {
			do {
				GamePreset entity = new GamePreset(cursor);
				result.add(entity);
			} while (cursor.moveToNext());
		}
		cursor.close();
		return result;
	}

	public boolean isInDb(String id) {
		boolean result = false;
		String sql = "SELECT count(*) from game_preset where id='" + id + "'";
		Cursor cursor = getDatabase().rawQuery(sql, null);
		cursor.moveToFirst();
		result = cursor.getInt(0) != 0;
		cursor.close();
		return result;
	}

	public GamePreset getPreset(String presetId) {
		GamePreset result = null;
		String sql = "select " + "id, game_path, name, dices from game_preset where id='" + presetId + "'";
		Cursor cursor = getDatabase().rawQuery(sql, null);
		if (cursor.moveToFirst()) {
			result = new GamePreset(cursor);
		}
		cursor.close();
		return result;
	}

}
